from PySide6.QtWidgets import QDialog,QMessageBox
from settings.publicvar import engine
from views.person.model.person import PersonOther, PersonBaseInfo
from views.person.other.operationother import Ui_operationother
from PySide6.QtCore import QDate
from sqlalchemy.orm import Session
from datetime import date

class OperationOther(QDialog,Ui_operationother):
    def __init__(self,is_start,data):
        super().__init__()
        self.setupUi(self)
        self.is_start = is_start
        self.loadDaliogData(data)
        self.if_state()
        self.name_id = 0
        self.changbtn.clicked.connect(self.changeDataFun)
        self.resetbtn.clicked.connect(self.resetDataFun)
        self.savebtn.clicked.connect(self.saveDataFun)
        self.name.editingFinished.connect(self.nameFinishedFun)
        self.deletebtn.clicked.connect(self.deleteDataFun)

    # 对话框标签及按钮初始化
    def if_state(self):
        self.name.setDisabled(True)
        if self.is_start == 'add':
            self.titlelable.setText('增加拓展信息')
            self.changbtn.hide()
            self.deletebtn.hide()
            self.name.setDisabled(False)
            self.IDcard.setText('身份证')
            self.name.setPlaceholderText('请先输入身份证，人员是否存在！')
        elif self.is_start ==  'change':
            self.titlelable.setText('修改拓展信息')
            self.savebtn.hide()
            self.deletebtn.hide()
        elif self.is_start == 'delete':
            self.titlelable.setText('删除拓展信息')
            self.savebtn.hide()
            self.changbtn.hide()
            self.resetbtn.hide()
        else:
            self.titlelable.setText('查看拓展信息')
            self.savebtn.hide()
            self.changbtn.hide()
            self.resetbtn.hide()
            self.deletebtn.hide()

    # 对话框数据加载
    def loadDaliogData(self,data):
        if data:
            self.idx.setText(data[0])
            self.name.setText(data[1])
            date = QDate.fromString(data[2], "yyyy-MM-dd")
            if date.isValid():
                self.birthday.setDate(date)
            else:
                self.birthday.setDate(QDate(1,1,1))
                self.birthday.setSpecialValueText("请选择日期")
            self.sex.setCurrentText(data[3])
            self.nation.setCurrentText(data[4])
            self.birthplace.setText(data[5])
            self.domicile.setText(data[6])
            self.residence.setText(data[7])
            self.file_number.setText(data[8])
            self.person_type.setText(data[9])
            self.mark.setText(data[10])

    # 修改数据
    def changeDataFun(self):
        with Session(engine) as session,session.begin():
            try:
                other = session.query(PersonOther).filter(PersonOther.id == self.idx.text()).one()
                birthday = self.birthday.date()
                other.birthday = date(birthday.year(),birthday.month(),birthday.day())
                other.sex = self.sex.currentText().strip()
                other.nation = self.nation.currentText().strip()
                other.birthplace = self.birthplace.text().strip()
                other.domicile = self.domicile.text().strip()
                other.residence = self.residence.text().strip()
                other.person_type = self.person_type.text().strip()
                other.file_number = self.file_number.text().strip()
                other.mark = self.mark.text().strip()
                QMessageBox.critical(None, '成功', '%s修改成功！' % self.name.text())
            except:
                QMessageBox.critical(None,'修改错误','你修改数据不存在，请重新操作！')
            self.close()

    # 重置数据
    def resetDataFun(self):
        self.birthday.setDate(QDate(1,1,1))
        self.birthday.setSpecialValueText("请选择日期")
        self.sex.setCurrentText('请选择性别')
        self.nation.setCurrentText('请选择民族')
        self.birthplace.setText('')
        self.domicile.setText('')
        self.residence.setText('')
        self.file_number.setText('')
        self.mark.setText('')

    # 增加数据
    def saveDataFun(self):
        with Session(engine) as session, session.begin():
            personother = PersonOther()
            personother.name_id = self.name_id
            birthday = self.birthday.date()
            personother.birthday = date(birthday.year(), birthday.month(), birthday.day())
            personother.sex = self.sex.currentText().strip()
            personother.nation = self.nation.currentText().strip()
            personother.birthplace = self.birthplace.text().strip()
            personother.domicile = self.domicile.text().strip()
            personother.residence = self.residence.text().strip()
            personother.person_type = self.person_type.text().strip()
            personother.file_number = self.file_number.text().strip()
            personother.mark = self.mark.text().strip()
            session.add(personother)
        QMessageBox.critical(None, '成功', '%s添加成功！' % self.name.text())
        self.close()

    def nameFinishedFun(self):
        IDcard = self.name.text().strip()
        with Session(engine) as session,session.begin():
            try:
                personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard == IDcard).one()
                if not personbase.personothers:
                    self.name.setText(personbase.name)
                    self.name_id = personbase.id
                else:
                    QMessageBox.critical(None, '失败', '数据已经增加了，不用添加！')
                    self.close()
            except:
                QMessageBox.critical(None,'失败','没有找到基本信息，请选增加基本信息,请检查身份证是否输错！')

    def deleteDataFun(self):
        idx = self.idx.text()
        with Session(engine) as session,session.begin():
            session.query(PersonOther).filter(PersonOther.id == idx).delete()
            QMessageBox.information(None,'成功','删除成功')